package xp2p.inter.client;

import java.io.IOException;
import java.io.Serializable;

import xp2p.inter.msg.BcastMessage;
import xp2p.inter.msg.CompleteRecvMessage;
import xp2p.inter.msg.CompleteRecvResponse;
import xp2p.inter.msg.SendMessage;
import xp2p.inter.msg.StartRecvMessage;

public class MessageClient
{
	private ClientRetryer client;

	public void send(Serializable data, int to) throws InnerException, IOException
	{
		SendMessage msg = new SendMessage();
		msg.setData(data);
		msg.To = to;
		msg.Tag = 0;
		msg.From = Statics.Rank;
		client.send(msg);
	}

	public void send(Serializable data, int to, long tag) throws InnerException, IOException
	{		
		SendMessage msg = new SendMessage();
		msg.setData(data);
		msg.To = to;
		msg.Tag = tag;
		msg.From = Statics.Rank;
		client.send(msg);
	}

	public void bcast(Serializable data) throws InnerException, IOException
	{
		BcastMessage msg = new BcastMessage();
		msg.setData(data);
		client.send(msg);
	}

	public long startRecv(int from, long tag) throws InnerException
	{
		StartRecvMessage msg = new StartRecvMessage();
		msg.From = from;
		msg.Tag = tag;
		return (Long) client.request(msg);
	}

	public long startRecv(long tag) throws InnerException
	{
		return startRecv(-1, tag);
	}

	public long startRecv(int from) throws InnerException
	{
		return startRecv(from, 0);
	}

	public long startRecv() throws InnerException
	{
		return startRecv(-1, 0);
	}

	public Serializable completeRecv(long messageId) throws InnerException, IOException, ClassNotFoundException
	{
		CompleteRecvMessage msg = new CompleteRecvMessage();
		msg.MessageId = messageId;
		CompleteRecvResponse msg1 = (CompleteRecvResponse)(client.request(msg));
		return msg1.getData();
	}
}
